package com.task.collector;


import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.task.util.HttpRequestUtils;
import com.task.util.HttpType;
import com.task.util.LogCacheUtil;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/*
 *
 * @description 自动签到控制器
 * @author carey
 * @date 2018/2/6 上午12:50
 * @version 1.0
 */
public class ClockCollector implements Runnable
{


    public  static final   LogCacheUtil logger= new  LogCacheUtil(ClockCollector.class,100);

    /* *
     * @author carey
     * @see  获取随机数
     * @date 2018/2/6 上午12:07
     * @param [min, max]
     * @return java.lang.String
     * @exception
     */
    private static Integer getRandom(int min, int max){
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;

    }

    private String fileUpLoad(MultipartFile file) throws IOException {
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create("E2T0q2nUMsnJyJYZG9_a6hcLH1M4RcfQL4yNGX5w", "eQXAMSoabj_azq2JY_SvCUJTxfIYMjtv4KGCP31S");
        UploadManager uploadManager = new UploadManager(cfg);
        DefaultPutRet putRet = null;
        Response response = null;
        response = uploadManager.put(file.getBytes(), (String)null, auth.uploadToken("kaoqin"));
        putRet = (DefaultPutRet) JSONObject.parseObject(response.bodyString(), DefaultPutRet.class);
        return putRet.hash;
    }



    public MultipartFile switchMultipartFile(File file){
        try {
            // File转换成MutipartFile
            FileInputStream inputStream = new FileInputStream(file);
            MultipartFile multipartFile = new MockMultipartFile(file.getName(), inputStream);
            //注意这里面填啥，MultipartFile里面对应的参数就有啥，比如我只填了name，则
            //MultipartFile.getName()只能拿到name参数，但是originalFilename是空。
            return multipartFile;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
    }

    public void run() {


        logger.logger("ClockCollector running....");

        Date date =new Date();
        date.getTime();

        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("YYYY-MM-dd");
        String toDate=simpleDateFormat.format(date);

        SimpleDateFormat endSimpleDateFormat=new SimpleDateFormat("YYYY-MM-dd HH:mm");
        String endTime=endSimpleDateFormat.format(date);

        File file=new File(this.getClass().getResource("/").getPath()+ "files/");

        String[] fileList=file.list();

        for(String fileName:fileList){
              //判断是否包含当天打卡图片，判断是否满足时间设置要求
            logger.logger("判断是否包含当天打卡图片:"+(-1!= fileName.indexOf(toDate)));
            logger.logger("判断是否满足时间设置要求:"+(fileName.substring(0,fileName.indexOf(".")).equals(endTime)));

            if(-1!= fileName.indexOf(toDate) && fileName.substring(0,fileName.indexOf(".")).equals(endTime)){

                   file=new File(this.getClass().getResource("/").getPath()+ "files/" + fileName);
                 try {
                     String imgId=this.fileUpLoad(switchMultipartFile(file));

                     HttpRequestUtils httpRequestUtils=new HttpRequestUtils(new HashMap<String, Object>());

                     Calendar c= Calendar.getInstance();
                     c.setTime(date);
                     int weekday=c.get(Calendar.DAY_OF_WEEK);
                     Integer second= getRandom(30,59);
                     String attendTime=fileName.substring(0,fileName.indexOf("."))+":"+second;
                     SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                     Date attendDate=dateFormat.parse(attendTime);


                     Map<String,Object> objectMap= new HashMap<>();
                     objectMap.put("attendTime",attendDate.getTime());
                     objectMap.put("userName","郑凯");
                     objectMap.put("userId","100005171");
                     objectMap.put("orgId","119118117");
                     objectMap.put("attendImgId",imgId);
                     objectMap.put("thisLatitude","32.042915035381796");
                     objectMap.put("thisLongitude","118.79217826555441");
                     objectMap.put("version","best");
                     objectMap.put("attendAddress","中山东路300号");
                     objectMap.put("type",2);
                     objectMap.put("week",weekday);
                     objectMap.put("attendorgName","南京长发考勤规则");
                     objectMap.put("attendorgId",78);
                     objectMap.put("PKCode","8A79CE2A9DBD37017A155AA79111CAAB");

                     String returnJson=httpRequestUtils.httpClient("https://gqkaoqin.gqget.com/attendConfig",objectMap, HttpType.POST);

                     System.out.println(returnJson);
                     logger.logger("返回报文："+ returnJson);
                     JSONObject jsonObject=JSONObject.parseObject(returnJson);

                     if(jsonObject.getString("message").equals("签到成功")){
                         if(file.delete()){
                             System.out.println(file.getPath()+":删除成功！");
                             logger.logger(file.getPath()+":删除成功！");
                             return;
                         }
                     }




                 } catch (IOException e) {
                     e.printStackTrace();
                 } catch (ParseException e) {
                     e.printStackTrace();
                 }

             }
        }
        logger.logger("ClockCollector end.....");
    }
}
